package sms_api

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/gogf/gf/v2/os/glog"
)

// SMS API版本信息
const (
	Version = "1.0.0"
	Name    = "SMS API"
)

// SMSClient SMS客户端
type SMSClient struct {
	service *SMSService
	config  *Config
	logger  *glog.Logger
}

// NewSMSClient 创建SMS客户端
func NewSMSClient(config *Config) (*SMSClient, error) {
	if config == nil {
		return nil, fmt.Errorf("配置不能为空")
	}

	// 创建SMS服务
	service, err := NewSMSService(config)
	if err != nil {
		return nil, fmt.Errorf("创建SMS服务失败: %w", err)
	}

	client := &SMSClient{
		service: service,
		config:  config,
		logger:  glog.New(),
	}

	return client, nil
}

// NewSMSClientFromEnv 从环境变量创建SMS客户端
func NewSMSClientFromEnv() (*SMSClient, error) {
	config, err := LoadConfigFromEnv()
	if err != nil {
		return nil, fmt.Errorf("从环境变量加载配置失败: %w", err)
	}

	return NewSMSClient(config)
}

// NewSMSClientFromFile 从配置文件创建SMS客户端
func NewSMSClientFromFile(configPath string) (*SMSClient, error) {
	config, err := LoadConfigFromFile(configPath)
	if err != nil {
		return nil, fmt.Errorf("从文件加载配置失败: %w", err)
	}

	return NewSMSClient(config)
}

// SendSMS 发送单条短信
func (c *SMSClient) SendSMS(ctx context.Context, req *SendSMSRequest) (*SendSMSResponse, error) {
	return c.service.SendSMS(ctx, req)
}

// SendBatchSMS 批量发送短信
func (c *SMSClient) SendBatchSMS(ctx context.Context, req *BatchSMSRequest) (*BatchSMSResponse, error) {
	return c.service.SendBatchSMS(ctx, req)
}

// QuerySMS 查询短信状态
func (c *SMSClient) QuerySMS(ctx context.Context, req *QuerySMSRequest) (*QuerySMSResponse, error) {
	return c.service.QuerySMS(ctx, req)
}

// GetMetrics 获取指标
func (c *SMSClient) GetMetrics() *MetricsResponse {
	return c.service.GetMetrics()
}

// HealthCheck 健康检查
func (c *SMSClient) HealthCheck(ctx context.Context) *HealthResponse {
	return c.service.HealthCheck(ctx)
}

// GetConfig 获取配置
func (c *SMSClient) GetConfig() *Config {
	return c.config
}

// Close 关闭客户端
func (c *SMSClient) Close() error {
	// 清理资源
	c.logger.Info(context.Background(), "SMS客户端关闭")
	return nil
}

// 便捷函数

// SendSimpleSMS 发送简单短信（使用默认配置）
func (c *SMSClient) SendSimpleSMS(ctx context.Context, phone, content string) (*SendSMSResponse, error) {
	req := &SendSMSRequest{
		Phone:     phone,
		Content:   content,
		Type:      SMSTypeText,
		Priority:  SMSPriorityNormal,
		MessageID: GenerateMessageID(),
	}

	return c.SendSMS(ctx, req)
}

// SendSMSWithSign 发送带签名的短信
func (c *SMSClient) SendSMSWithSign(ctx context.Context, phone, content, sign string) (*SendSMSResponse, error) {
	req := &SendSMSRequest{
		Phone:     phone,
		Content:   content,
		Sign:      sign,
		Type:      SMSTypeText,
		Priority:  SMSPriorityNormal,
		MessageID: GenerateMessageID(),
	}

	return c.SendSMS(ctx, req)
}

// SendUrgentSMS 发送紧急短信
func (c *SMSClient) SendUrgentSMS(ctx context.Context, phone, content string) (*SendSMSResponse, error) {
	req := &SendSMSRequest{
		Phone:     phone,
		Content:   content,
		Type:      SMSTypeText,
		Priority:  SMSPriorityHigh,
		MessageID: GenerateMessageID(),
	}

	return c.SendSMS(ctx, req)
}

// SendVerificationCode 发送验证码
func (c *SMSClient) SendVerificationCode(ctx context.Context, phone, code string) (*SendSMSResponse, error) {
	content := fmt.Sprintf("您的验证码是：%s，请在5分钟内使用。如非本人操作，请忽略此短信。", code)

	req := &SendSMSRequest{
		Phone:     phone,
		Content:   content,
		Type:      SMSTypeVerification,
		Priority:  SMSPriorityHigh,
		MessageID: GenerateMessageID(),
		Metadata: map[string]interface{}{
			"code":     code,
			"purpose": "verification",
			"expires": time.Now().Add(5 * time.Minute).Unix(),
		},
	}

	return c.SendSMS(ctx, req)
}

// SendNotification 发送通知短信
func (c *SMSClient) SendNotification(ctx context.Context, phone, title, content string) (*SendSMSResponse, error) {
	message := content
	if title != "" {
		message = fmt.Sprintf("【%s】%s", title, content)
	}

	req := &SendSMSRequest{
		Phone:     phone,
		Content:   message,
		Type:      SMSTypeNotification,
		Priority:  SMSPriorityNormal,
		MessageID: GenerateMessageID(),
		Metadata: map[string]interface{}{
			"title":   title,
			"purpose": "notification",
		},
	}

	return c.SendSMS(ctx, req)
}

// SendMarketingSMS 发送营销短信
func (c *SMSClient) SendMarketingSMS(ctx context.Context, phone, content string) (*SendSMSResponse, error) {
	req := &SendSMSRequest{
		Phone:     phone,
		Content:   content,
		Type:      SMSTypeMarketing,
		Priority:  SMSPriorityLow,
		MessageID: GenerateMessageID(),
		Metadata: map[string]interface{}{
			"purpose": "marketing",
		},
	}

	return c.SendSMS(ctx, req)
}

// BatchSendToPhones 批量发送到多个手机号（相同内容）
func (c *SMSClient) BatchSendToPhones(ctx context.Context, phones []string, content string) (*BatchSMSResponse, error) {
	requests := make([]*SendSMSRequest, len(phones))
	for i, phone := range phones {
		requests[i] = &SendSMSRequest{
			Phone:     phone,
			Content:   content,
			Type:      SMSTypeText,
			Priority:  SMSPriorityNormal,
			MessageID: GenerateMessageID(),
		}
	}

	req := &BatchSMSRequest{
		BatchID:  GenerateBatchID(),
		Requests: requests,
	}

	return c.SendBatchSMS(ctx, req)
}

// 全局便捷函数（使用默认客户端）

var defaultClient *SMSClient

// InitDefaultClient 初始化默认客户端
func InitDefaultClient(config *Config) error {
	client, err := NewSMSClient(config)
	if err != nil {
		return err
	}
	defaultClient = client
	return nil
}

// InitDefaultClientFromEnv 从环境变量初始化默认客户端
func InitDefaultClientFromEnv() error {
	client, err := NewSMSClientFromEnv()
	if err != nil {
		return err
	}
	defaultClient = client
	return nil
}

// GetDefaultClient 获取默认客户端
func GetDefaultClient() *SMSClient {
	return defaultClient
}

// SendSMS 使用默认客户端发送短信
func SendSMS(ctx context.Context, req *SendSMSRequest) (*SendSMSResponse, error) {
	if defaultClient == nil {
		return nil, fmt.Errorf("默认客户端未初始化，请先调用 InitDefaultClient")
	}
	return defaultClient.SendSMS(ctx, req)
}

// SendSimpleSMS 使用默认客户端发送简单短信
func SendSimpleSMS(ctx context.Context, phone, content string) (*SendSMSResponse, error) {
	if defaultClient == nil {
		return nil, fmt.Errorf("默认客户端未初始化，请先调用 InitDefaultClient")
	}
	return defaultClient.SendSimpleSMS(ctx, phone, content)
}

// SendVerificationCode 使用默认客户端发送验证码
func SendVerificationCode(ctx context.Context, phone, code string) (*SendSMSResponse, error) {
	if defaultClient == nil {
		return nil, fmt.Errorf("默认客户端未初始化，请先调用 InitDefaultClient")
	}
	return defaultClient.SendVerificationCode(ctx, phone, code)
}

// 工具函数

// ValidatePhone 验证手机号格式
func ValidatePhone(phone string) error {
	return validatePhone(phone)
}

// ValidateContent 验证短信内容
func ValidateContent(content string) error {
	return validateContent(content)
}

// ValidateSign 验证签名
func ValidateSign(sign string) error {
	return validateSign(sign)
}

// EstimateCost 估算短信费用
func EstimateCost(content, smsType string) float64 {
	return estimateCost(content, smsType)
}

// FormatPhone 格式化手机号
func FormatPhone(phone string) string {
	return formatPhone(phone)
}

// 示例和测试函数

// Example 使用示例
func Example() {
	// 1. 从环境变量初始化客户端
	err := InitDefaultClientFromEnv()
	if err != nil {
		fmt.Printf("初始化客户端失败: %v\n", err)
		return
	}

	ctx := context.Background()

	// 2. 发送简单短信
	resp, err := SendSimpleSMS(ctx, "+8618888888888", "这是一条测试短信")
	if err != nil {
		fmt.Printf("发送短信失败: %v\n", err)
		return
	}
	fmt.Printf("短信发送成功: %+v\n", resp)

	// 3. 发送验证码
	resp, err = SendVerificationCode(ctx, "+8618888888888", "123456")
	if err != nil {
		fmt.Printf("发送验证码失败: %v\n", err)
		return
	}
	fmt.Printf("验证码发送成功: %+v\n", resp)

	// 4. 查询短信状态
	client := GetDefaultClient()
	queryResp, err := client.QuerySMS(ctx, &QuerySMSRequest{
		MessageID: resp.MessageID,
		Phone:     "+8618888888888",
	})
	if err != nil {
		fmt.Printf("查询短信状态失败: %v\n", err)
		return
	}
	fmt.Printf("短信状态: %+v\n", queryResp)

	// 5. 获取指标
	metrics := client.GetMetrics()
	fmt.Printf("服务指标: %+v\n", metrics)
}

// TestSMSAPI 测试SMS API功能
func TestSMSAPI() error {
	// 创建测试配置
	config := &Config{
		Service: ServiceConfig{
			Name:    "SMS API Test",
			Version: Version,
			Port:    8080,
		},
		DefaultProvider: "space_iot",
		SpaceIoT: SpaceIoTConfig{
			Enabled: true,
			BaseURL: "https://sms.space-iot.net/api",
			Sign:    os.Getenv("SPACE_IOT_SIGN"),
			Key:     os.Getenv("SPACE_IOT_KEY"),
			Timeout: 30 * time.Second,
		},
		Retry: RetryConfig{
			MaxRetries: 3,
			BaseDelay:  time.Second,
			MaxDelay:   10 * time.Second,
			Multiplier: 2.0,
		},
		RateLimit: RateLimitConfig{
			RequestsPerSecond: 10,
			BurstSize:         20,
		},
		Batch: BatchConfig{
			MaxSize:    100,
			Timeout:    30 * time.Second,
			Concurrent: 5,
		},
		Cache: CacheConfig{
			Enabled: true,
			TTL:     5 * time.Minute,
		},
	}

	// 创建客户端
	client, err := NewSMSClient(config)
	if err != nil {
		return fmt.Errorf("创建客户端失败: %w", err)
	}
	defer client.Close()

	ctx := context.Background()

	// 测试健康检查
	health := client.HealthCheck(ctx)
	fmt.Printf("健康检查: %+v\n", health)

	// 测试发送短信
	resp, err := client.SendSimpleSMS(ctx, "+8618888888888", "SMS API测试消息")
	if err != nil {
		return fmt.Errorf("发送短信失败: %w", err)
	}
	fmt.Printf("短信发送成功: %+v\n", resp)

	// 测试获取指标
	metrics := client.GetMetrics()
	fmt.Printf("服务指标: %+v\n", metrics)

	return nil
}